package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.ext.PaasCommentEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.PaasFormDataHelper;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.StageLogHelp;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.model.PaasCommentModel;
import com.xbongbong.paas.service.CustomerRuleService;
import com.xbongbong.paas.service.PublicGroupSyncService;
import com.xbongbong.paas.service.TransferBackRuleScriptService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FocusDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.listbatch.pojo.dto.ListBatchDTO;
import com.xbongbong.pro.message.constant.CustomerPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.pojo.dto.PublicGroupRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.pro.opportunity.pojo.JudgeStageChangedPojo;
import com.xbongbong.pro.score.pojo.dto.DataScoreUpdateSingleDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CustomerStageLogEntity;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.LikeEntity;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.ClueRuleSettingEnum;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.PublicEnum;
import com.xbongbong.saas.help.workflow.CustomerStageLogHelp;
import com.xbongbong.saas.help.workflow.MarketActivityForStaticHelp;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerStageLogModel;
import com.xbongbong.saas.model.CustomerStageModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.LikeModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.service.ConsistencySyncService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.CustomerService;
import com.xbongbong.saas.service.ListBatchService;
import com.xbongbong.saas.service.ScoreCalculateService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.help.saas.WorkFlowSaasStageHelp;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowCustomerStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {


    @Resource
    private UserModel userModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private PaasCommentModel paasCommentModel;
    @Resource
    private LikeModel likeModel;
    @Resource
    private CustomerStageLogModel customerStageLogModel;
    @Resource
    private CustomerStageModel customerStageModel;
    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private ScoreCalculateService scoreCalculateService;
    @Resource
    private CustomerStageLogHelp customerStageLogHelp;
    @Resource
    private MarketActivityForStaticHelp marketActivityForStaticHelp;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private MessageService messageService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private StageLogHelp stageLogHelp;
    @Resource
    private WorkFlowSaasStageHelp workFlowSaasStageHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PublicGroupSyncService publicGroupSyncService;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private ConsistencySyncService consistencySyncService;
    @Resource
    private ListBatchService listBatchService;
    @Resource
    private CustomerRuleService customerRuleService;
    @Resource
    private TransferBackRuleScriptService transferBackRuleScriptService;
    @Resource
    private PaasFormDataHelper paasFormDataHelper;


    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        Long formId = pojoData.getFormId();
        User user = workflowTransferPOJO.getUser();
        String creatorId = user.getUserId();
        UserEntity creatorUser = userModel.getByKeyIngoreDel(creatorId, corpid);

        CustomerEntityExt customerEntityExt = customerModel.getByKey(dataId, corpid);


        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
        String stageCode = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), "");
        Integer reasonId = FastJsonHelper.getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.WASTAGE.getAttr(), BasicConstant.ZERO);
        String wastageMemo = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.WASTAGE_MEMO.getAttr(), "");


        try {
            List<String> customerUserIdList = customerUserModel.getCustomerUserIdList(corpid, Arrays.asList(dataId), BasicConstant.ONE);
             Integer operate = workflowTransferPOJO.getOperate();
            Integer isPublic = data.getInteger(ClueEnum.IS_PUBLIC.getAttr());
            if (!(Objects.equals(operate, WorkflowOperateEnum.ADD.getType()) && Objects.equals(isPublic, BasicConstant.ONE)) && CollectionsUtil.isEmpty(customerUserIdList)) {
                ListBatchDTO listBatchDTO = new ListBatchDTO();
                listBatchDTO.setCorpid(corpid);
                listBatchDTO.setUserId(creatorId);
                listBatchDTO.setLoginUserName(user.getName());
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(creatorUser, userVO);
                userVO.getPermSet().add(ProPermissionAliasEnum.CUSTOMER_BACK.getAlias());
                listBatchDTO.setLoginUser(userVO);
                listBatchDTO.setDataIdList(Collections.singletonList(dataId));
                listBatchDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                listBatchDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                listBatchDTO.setFormId(pojoData.getFormId());
                listBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                listBatchService.backCustomer(listBatchDTO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCustomerStrategy.save customerService.backCustomer error", e);
        }

        JudgeStageChangedPojo judgeStageChangedPojo = null;

        try {
            if (Objects.equals(pojoData.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_FOCUS.getCode())) {
                FocusDTO focusDTO = new FocusDTO();
                focusDTO.setBusinessType(pojoData.getBusinessType());
                focusDTO.setCorpid(corpid);
                focusDTO.setUserId(user.getUserId());
                focusDTO.setDataIdList(Collections.singletonList(dataId));
                focusDTO.setFocus(1);
                focusDTO.setFromNew(BasicConstant.ONE);
                focusDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerService.focus(focusDTO);
            }
        } catch (Exception e) {
            log.error("新建重点客户关注", e);
        }


        try {
            if(isNotDistributeBusinessType(workflowTransferPOJO)) {
                judgeStageChangedPojo = stageLogHelp.judgeStageChanged(corpid, formId, dataId, stageCode, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                // 客户创建项目日志
                String isPublic = data.getString(CustomerManagementEnum.IS_PUBLIC.getAttr());
                PaasFormEntity paasForm = proFormHelp.getPaasForm(pojoData.getFormId(), pojoData.getBusinessType(), corpid);
                String paasFormName = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getName();
                if (Objects.nonNull(paasForm)) {
                    paasFormName = paasForm.getName();
                }
                String publicName = Objects.equals(isPublic, String.valueOf(PublicEnum.PUBLIC.getCode())) ? PublicEnum.PUBLIC.getName() : paasFormName;
                String creatorUserName = Objects.isNull(creatorUser) ? "" : creatorUser.getName();
                String memo;
                String communicateMemo;
                if (Objects.equals(workflowTransferPOJO.getIsImport(), BasicConstant.ONE)) {
                    if (StringUtil.isNotEmpty(stageCode) && Objects.nonNull(judgeStageChangedPojo)) {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT_STAGE;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUserName, publicName, judgeStageChangedPojo.getTargetStageName());
                    } else {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUserName, publicName, customerName);
                    }
                } else {
                    if (StringUtil.isNotEmpty(stageCode) && Objects.nonNull(judgeStageChangedPojo)) {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_ADD_STAGE;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUserName, publicName, judgeStageChangedPojo.getTargetStageName());
                    } else {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_ADD;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUserName, publicName, customerName);
                    }
                }
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCustomerId(dataId);
                customerDynamicAddDTO.setCustomerName(customerName);
                customerDynamicAddDTO.setDataId(0L);
                customerDynamicAddDTO.setCommunicateBusinessType(null);
                customerDynamicAddDTO.setCommunicateBusinessText("");
                customerDynamicAddDTO.setLogType(ProjectLogEnum.CUSTOMER_CREATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }else {
                // 客户创建项目日志
                String isPublic = data.getString(CustomerManagementEnum.IS_PUBLIC.getAttr());
                String publicName = Objects.equals(isPublic, String.valueOf(PublicEnum.PUBLIC.getCode())) ? PublicEnum.PUBLIC.getName() : XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getName();
                String operate = Objects.equals(workflowTransferPOJO.getIsImport(), BasicConstant.ONE) ? I18nMessageUtil.getMessage(I18nStringConstant.IMPORTED) : I18nMessageUtil.getMessage(I18nStringConstant.ADD);
                String creatorUserName = Objects.isNull(creatorUser) ? "" : creatorUser.getName();
                String communicateMemo = creatorUserName + operate + publicName + ":" + customerName;

                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCustomerId(dataId);
                customerDynamicAddDTO.setCustomerName(customerName);
                customerDynamicAddDTO.setDataId(0L);
                customerDynamicAddDTO.setCommunicateBusinessType(null);
                customerDynamicAddDTO.setCommunicateBusinessText("");
                customerDynamicAddDTO.setLogType(ProjectLogEnum.CUSTOMER_CREATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerDynamicAddDTO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }
        } catch (Exception e) {
            log.error("客户创建项目日志", e);
        }

        try {
            if (!Objects.equals(workflowTransferPOJO.getIsImport(), 1)) {
                // 客户创建消息推送
                List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.CUSTOMER_ADD_PUSH.getCode(), PushTypeEnum.CUSTOMER_ADD_PUSH.getSubCode(), creatorUser, customerEntityExt);
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
                MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_ADD_TITLE), String.format(I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_ADD_CONTENT), creatorUser.getName(), customerName), null, options);
                messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.CUSTOMER_ADD_PUSH);
            }
        } catch (Exception e) {
            log.error("客户创建消息推送", e);
        }

        try {
//            Integer isBringCustomer = saasFormSaveDTO.getIsBringCustomer();
//            Long clueId = saasFormSaveDTO.getClueId();
            Integer isBringCustomer = data.getInteger("isBringCustomer");
            Long clueId = data.getLong("clueId");
            if (Objects.nonNull(clueId) && clueId > 0) {
                // 线索转换后需要更新线索状态为已转换,并设置已转换的客户id，方便市场活动统计线索的时候用
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ClueEnum.CLUE_STATUS.getAttr(), ClueStatusEnum.TRANSFORMED.getCode());
                ClueEntityExt clueEntityExt = clueModel.getByKey(clueId, corpid);
                if (Objects.nonNull(clueEntityExt)) {
//                    if (isNew) {
                    Boolean flag = proFormHelp.getClueSingleRuleList(corpid, ClueRuleSettingEnum.NEW_CUSTOMER_CREATE_TIME.getConfig(), clueEntityExt.getFormId());
                    if (flag) {
                        // 线索模板设计界面，更新最后跟进时间规则中的“线索转换新建的客户，取其创建时间更新”规则开启，才更新线索的最后跟进时间
                        param.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), customerEntityExt.getAddTime());
                    }
//                    }
                    clueModel.jsonsetNoSubById(corpid, clueId, param);
                    if (Objects.equals(isBringCustomer, 1)) {
                        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                        BoolQueryBuilder queryBuilder = boolQuery();
                        queryBuilder.filter(termQuery("corpid.keyword", corpid));
                        queryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
                        queryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE), XbbRefTypeEnum.CLUE.getCode()));
                        queryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS), clueId));
                        queryBuilder.filter(termQuery("logType", 0));
                        queryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getType()));
                        searchSourceBuilder.query(queryBuilder);
                        List<String> fieldList = new ArrayList<>();
                        fieldList.add(FieldTypeEnum.DATAID.getAlias());
                        List<PaasFormDataEntityExt> entityExts = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE, fieldList, null, null);
                        if (CollectionsUtil.isNotEmpty(entityExts)) {
                            List<Long> dataIds = new ArrayList<>();
                            entityExts.forEach(item -> dataIds.add(item.getDataId()));
                            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            map.put("corpid", corpid);
                            map.put("idIn", dataIds);
                            map.put("del", 0);
                            List<CustomerCommunicateEntityExt> entitys = customerCommunicateModel.findEntitys(map);
                            Long appId = 0L;
                            for (CustomerCommunicateEntityExt entityExt : entitys) {
                                JSONObject data1 = entityExt.getData();
                                data1.remove(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr());
                                data1.remove(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr());
                                data1.remove(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
                                data1.put(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), dataId);
                                data1.put(CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), customerName);
                                entityExt.setOriginalId(entityExt.getDataId());
                                entityExt.setId(null);
                                appId = entityExt.getAppId();
                            }
                            if (CollectionsUtil.isNotEmpty(entityExts)) {
                                // 复制线索的跟进记录给客户
                                customerCommunicateModel.insertBatch(entitys);
                                // 复制线索的跟进记录的评论带到客户跟进记录里
                                Map<Long, Long> entityIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                entitys.forEach(item -> entityIdMap.put(item.getOriginalId(), item.getId()));
                                Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                paramMap.put("corpid", corpid);
                                paramMap.put("type", BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
                                paramMap.put("appId", appId);
                                paramMap.put("refIdIn", dataIds);
                                paramMap.put("del", 0);
                                List<PaasCommentEntityExt> comments = paasCommentModel.findEntitys(paramMap);
                                if (CollectionsUtil.isNotEmpty(comments)) {
                                    for (PaasCommentEntityExt comment : comments) {
                                        comment.setId(null);
                                        comment.setRefId(entityIdMap.get(comment.getRefId()));
                                    }
                                    paasCommentModel.insertBatch(comments);
                                }
                                // 复制线索的跟进记录的点赞带到客户跟进记录里
                                Map<String, Object> likeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                likeMap.put("corpid", corpid);
                                likeMap.put("appId", appId);
                                likeMap.put("type", BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
                                likeMap.put("refIdIn", dataIds);
                                likeMap.put("del", 0);
                                List<LikeEntity> likeEntityList = likeModel.findEntitys(likeMap);
                                if (CollectionsUtil.isNotEmpty(likeEntityList)) {
                                    for (LikeEntity likeEntity : likeEntityList) {
                                        likeEntity.setId(null);
                                        likeEntity.setRefId(entityIdMap.get(likeEntity.getRefId()));
                                    }
                                    likeModel.insertBatch(likeEntityList);
                                }
                            }
                        }
                    }
                }
                //评分更新(线索转化客户之后，会在此处修改线索状态)
                DataScoreUpdateSingleDTO dataScoreUpdateBatchDTO = new DataScoreUpdateSingleDTO();
                dataScoreUpdateBatchDTO.setCorpid(corpid);
                dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
                dataScoreUpdateBatchDTO.setDataId(clueId);
                dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                scoreCalculateService.updateSingle(dataScoreUpdateBatchDTO);
            }
        } catch (XbbException e) {
            log.error("线索转换客户，并将线索的跟进记录带到客户", e);
        }
        Long now = DateTimeUtil.getInt();


        if(Objects.isNull(judgeStageChangedPojo)) {
            judgeStageChangedPojo = stageLogHelp.judgeStageChanged(corpid, formId, dataId, stageCode, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        }
        if (judgeStageChangedPojo.getIsStageChanged()) {
            try {
                workFlowSaasStageHelp.workFlowStageJump(workflowTransferPOJO, CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), null);
            } catch (Exception e) {
                log.error("客户阶段变更消息推送", e);
            }
        }
        try {
            //评分更新（客户的编辑，底层是走到这里。客户的导入比较特殊，是在另一处 ExcelImportServiceImpl.insert）
            DataScoreUpdateSingleDTO dataScoreUpdateBatchDTO = new DataScoreUpdateSingleDTO();
            dataScoreUpdateBatchDTO.setCorpid(corpid);
            dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
            dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            dataScoreUpdateBatchDTO.setDataId(dataId);
            dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            scoreCalculateService.updateSingle(dataScoreUpdateBatchDTO);
        } catch (Exception e) {
            log.error("e{}", e.getMessage());
        }

        try {
            //根据分组规则绑定所属分组
            boolean publicPoolSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
            if (publicPoolSeniorModel && !Objects.equals(workflowTransferPOJO.getIsImport(), 1)) {
                PublicGroupRabbitMqDTO mqDTO = new PublicGroupRabbitMqDTO(corpid, Collections.singletonList(dataId), formId,  XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                publicGroupSyncService.bindPublicGroupByMq(mqDTO);
            }
        } catch (Exception e) {
            log.error("绑定公海分组失败", e);
        }


        // 添加市场活动
        marketActivityForStaticHelp.addMarketActivity(customerEntityExt, XbbRefTypeEnum.CUSTOMER_MANAGEMENT);

        // 批量编辑/新建联系人

        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(creatorUser, userVO);
        paasFormDataHelper.batchEditContact(saasNeedRedundantAttrPojo, userVO, user.getUserId(), corpid, dataId, data.getString(CustomerManagementEnum.NAME.getAttr()), workflowTransferPOJO.getIsImport(), ContactEnum.CUSTOMER_NAME.getAttr(), XbbRefTypeEnum.CONTACT);

        addLinkDataDynamic(workflowTransferPOJO);
        // api
        apiHook(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        Long formId = pojoData.getFormId();
        User user = workflowTransferPOJO.getUser();
        String creatorId = user.getUserId();
        UserEntity creator = userModel.getByKeyIngoreDel(creatorId, corpid);


        CustomerEntityExt customerEntityExt = customerModel.getByKey(dataId, corpid);


        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
        JSONObject oldData = workflowBackupDataEntity.getData();

        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
        String stageCode = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), "");
        String oldStageCode = FastJsonHelper.getStringOrDefaultFromFormData(oldData, CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), "");
        Integer reasonId = FastJsonHelper.getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.WASTAGE.getAttr(), BasicConstant.ZERO);
        Integer oldReasonId = FastJsonHelper.getIntegerOrDefaultFromFormData(oldData, CustomerManagementEnum.WASTAGE.getAttr(), BasicConstant.ZERO);
        String wastageMemo = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.WASTAGE_MEMO.getAttr(), "");


        try {
            List<String> customerUserIdList = customerUserModel.getCustomerUserIdList(corpid, Arrays.asList(dataId), BasicConstant.ONE);
            if (CollectionsUtil.isEmpty(customerUserIdList)) {

                if (Objects.nonNull(workflowBackupDataEntity)) {
                    // 工作流退回公海池团队数据特殊操作，因为在工作流内团队数据实时更新，已经没有前负责人的数据，需要再生成一份数据
                    JSONObject backupData = workflowBackupDataEntity.getData();
                    JSONArray jsonArray = backupData.getJSONArray(StringConstant.USER_TEAM);
                    List<CustomerUserEntity> userEntities = JSON.parseArray(jsonArray.toJSONString(), CustomerUserEntity.class);
                    userEntities.forEach(v -> v.setId(null));
                    customerUserModel.insertBatch(userEntities, true);
                }

                ListBatchDTO listBatchDTO = new ListBatchDTO();
                listBatchDTO.setCorpid(corpid);
                listBatchDTO.setUserId(creatorId);
                listBatchDTO.setLoginUserName(user.getName());
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(creator, userVO);
                userVO.getPermSet().add(ProPermissionAliasEnum.CUSTOMER_BACK.getAlias());
                listBatchDTO.setLoginUser(userVO);
                listBatchDTO.setDataIdList(Collections.singletonList(dataId));
                listBatchDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                listBatchDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                listBatchDTO.setFormId(pojoData.getFormId());
                listBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                listBatchService.backCustomer(listBatchDTO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCustomerStrategy.update customerService.backCustomer error", e);
        }


        try {
            String oldCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, CustomerManagementEnum.NAME.getAttr(), "");
            if (!Objects.equals(customerName, oldCustomerName)) {
                log.info("customer update customer name : corpid= " + corpid + ">dataId=" + dataId + ">newName="+ customerName + ">oldName="+ oldCustomerName);
                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, dataId, customerName);
                consistencySyncService.syncCustomer(consistencySyncRabbitMqDTO);
            }
        } catch (Exception e) {
            log.error("客户一致性同步失败", e);
        }

        try {
            if (!Objects.equals(oldData.getString(CustomerManagementEnum.TYPE.getAttr()), data.getString(CustomerManagementEnum.TYPE.getAttr()))) {
                if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)) {
                    transferBackRuleScriptService.deletePublicSeniorTag(corpid, Collections.singletonList(dataId), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), customerEntityExt.getFormId());
                } else {
                    customerRuleService.deletePublicTag(corpid, Collections.singletonList(dataId));

                }
                 String type = dataDictionaryModel.getDictionaryValue(corpid, DictionaryEnum.CUSTOMER_STATUS, data.getInteger(CustomerManagementEnum.TYPE.getAttr()));
                // 客户状态变更消息推送
                List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.CUSTOMER_CHANGE_PUSH.getCode(), PushTypeEnum.CUSTOMER_CHANGE_PUSH.getSubCode(), creator, customerEntityExt);
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
                MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_STATUS_CHANGE_TITLE), String.format(I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_STATUS_CHANGE_CONTENT), user.getName(), customerName, type), null, options);
                messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.CUSTOMER_CHANGE_PUSH);
            }
        } catch (Exception e) {
            log.error("客户状态变更消息推送", e);
        }

        try {
//            Integer isBringCustomer = saasFormSaveDTO.getIsBringCustomer();
//            Long clueId = saasFormSaveDTO.getClueId();
            Integer isBringCustomer = data.getInteger("isBringCustomer");
            Long clueId = data.getLong("clueId");
            if (Objects.nonNull(clueId) && clueId > 0) {
                // 线索转换后需要更新线索状态为已转换,并设置已转换的客户id，方便市场活动统计线索的时候用
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ClueEnum.CLUE_STATUS.getAttr(), ClueStatusEnum.TRANSFORMED.getCode());
                ClueEntityExt clueEntityExt = clueModel.getByKey(clueId, corpid);
                if (Objects.nonNull(clueEntityExt)) {
//                    if (isNew) {
//                        Boolean flag = paasFormService.getClueSingleRuleList(corpid, ClueRuleSettingEnum.NEW_CUSTOMER_CREATE_TIME.getConfig(), clueEntityExt.getFormId());
//                        if (flag) {
//                            // 线索模板设计界面，更新最后跟进时间规则中的“线索转换新建的客户，取其创建时间更新”规则开启，才更新线索的最后跟进时间
//                            param.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), newPaasFormDataEntity.getAddTime());
//                        }
//                    }
                    clueModel.jsonsetNoSubById(corpid, clueId, param);
                    if (Objects.equals(isBringCustomer, 1)) {
                        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                        BoolQueryBuilder queryBuilder = boolQuery();
                        queryBuilder.filter(termQuery("corpid.keyword", corpid));
                        queryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
                        queryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE), XbbRefTypeEnum.CLUE.getCode()));
                        queryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS), clueId));
                        queryBuilder.filter(termQuery("logType", 0));
                        queryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getType()));
                        searchSourceBuilder.query(queryBuilder);
                        List<String> fieldList = new ArrayList<>();
                        fieldList.add(FieldTypeEnum.DATAID.getAlias());
                        List<PaasFormDataEntityExt> entityExts = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE, fieldList, null, null);
                        if (CollectionsUtil.isNotEmpty(entityExts)) {
                            List<Long> dataIds = new ArrayList<>();
                            entityExts.forEach(item -> dataIds.add(item.getDataId()));
                            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            map.put("corpid", corpid);
                            map.put("idIn", dataIds);
                            map.put("del", 0);
                            List<CustomerCommunicateEntityExt> entitys = customerCommunicateModel.findEntitys(map);
                            Long appId = 0L;
                            for (CustomerCommunicateEntityExt entityExt : entitys) {
                                JSONObject data1 = entityExt.getData();
                                data1.remove(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr());
                                data1.remove(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr());
                                data1.remove(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
                                data1.put(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), dataId);
                                data1.put(CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), customerName);
                                entityExt.setOriginalId(entityExt.getDataId());
                                entityExt.setId(null);
                                appId = entityExt.getAppId();
                            }
                            if (CollectionsUtil.isNotEmpty(entityExts)) {
                                // 复制线索的跟进记录给客户
                                customerCommunicateModel.insertBatch(entitys);
                                // 复制线索的跟进记录的评论带到客户跟进记录里
                                Map<Long, Long> entityIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                entitys.forEach(item -> entityIdMap.put(item.getOriginalId(), item.getId()));
                                Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                paramMap.put("corpid", corpid);
                                paramMap.put("type", BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
                                paramMap.put("appId", appId);
                                paramMap.put("refIdIn", dataIds);
                                paramMap.put("del", 0);
                                List<PaasCommentEntityExt> comments = paasCommentModel.findEntitys(paramMap);
                                if (CollectionsUtil.isNotEmpty(comments)) {
                                    for (PaasCommentEntityExt comment : comments) {
                                        comment.setId(null);
                                        comment.setRefId(entityIdMap.get(comment.getRefId()));
                                    }
                                    paasCommentModel.insertBatch(comments);
                                }
                                // 复制线索的跟进记录的点赞带到客户跟进记录里
                                Map<String, Object> likeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                likeMap.put("corpid", corpid);
                                likeMap.put("appId", appId);
                                likeMap.put("type", BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
                                likeMap.put("refIdIn", dataIds);
                                likeMap.put("del", 0);
                                List<LikeEntity> likeEntityList = likeModel.findEntitys(likeMap);
                                if (CollectionsUtil.isNotEmpty(likeEntityList)) {
                                    for (LikeEntity likeEntity : likeEntityList) {
                                        likeEntity.setId(null);
                                        likeEntity.setRefId(entityIdMap.get(likeEntity.getRefId()));
                                    }
                                    likeModel.insertBatch(likeEntityList);
                                }
                            }
                        }
                    }
                }
                //评分更新(线索转化客户之后，会在此处修改线索状态)
                DataScoreUpdateSingleDTO dataScoreUpdateBatchDTO = new DataScoreUpdateSingleDTO();
                dataScoreUpdateBatchDTO.setCorpid(corpid);
                dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
                dataScoreUpdateBatchDTO.setDataId(clueId);
                dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                scoreCalculateService.updateSingle(dataScoreUpdateBatchDTO);
            }
        } catch (XbbException e) {
            log.error("线索转换客户，并将线索的跟进记录带到客户", e);
        }
        Long now = DateTimeUtil.getInt();

        // 编辑客户的时候没有变更阶段但是修改了流失原因，则将流失原因更新到阶段记录中
        if (!Objects.equals(reasonId, oldReasonId) && StringUtil.isNotEmpty(stageCode) && Objects.equals(stageCode, oldStageCode)) {
            customerStageLogHelp.updateStageLogReasonId(corpid, formId, dataId, stageCode, reasonId, wastageMemo);
        }

        JudgeStageChangedPojo judgeStageChangedPojo = stageLogHelp.judgeStageChanged(corpid, formId, dataId, stageCode, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        if (judgeStageChangedPojo.getIsStageChanged()) {
            try {

                //跳转前的阶段需要从log表中实时去查一下，工作流的流转数据已经被更新过了，不能从那里拿
                CustomerStageLogEntity customerStageLogEntity = customerStageLogModel.getIsNowStage(corpid, formId, dataId);
                PaasStageEntity customerStageEntity = null;
                if ( !Objects.isNull(customerStageLogEntity)) {
                    Long stageId = customerStageLogEntity.getStageId();
                    customerStageEntity = customerStageModel.getByKey(stageId, corpid);
                }

                workFlowSaasStageHelp.workFlowStageJump(workflowTransferPOJO, CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), customerStageEntity);
            } catch (Exception e) {
                log.error("客户阶段变更消息推送", e);
            }
        }
        try {
            //评分更新（客户的编辑，底层是走到这里。客户的导入比较特殊，是在另一处 ExcelImportServiceImpl.insert）
            DataScoreUpdateSingleDTO dataScoreUpdateBatchDTO = new DataScoreUpdateSingleDTO();
            dataScoreUpdateBatchDTO.setCorpid(corpid);
            dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
            dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            dataScoreUpdateBatchDTO.setDataId(dataId);
            dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            scoreCalculateService.updateSingle(dataScoreUpdateBatchDTO);
        } catch (Exception e) {
            log.error("e{}", e.getMessage());
        }


        // 添加市场活动  客户更新不需要更新市场活动中间表
        //marketActivityForStaticHelp.addMarketActivity(customerEntityExt, XbbRefTypeEnum.CUSTOMER_MANAGEMENT);

        // 批量编辑/新建联系人
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(creator, userVO);
        paasFormDataHelper.batchEditContactForUpdate(saasNeedRedundantAttrPojo, userVO, creatorId, corpid, dataId, data.getString(CustomerManagementEnum.NAME.getAttr()), workflowTransferPOJO.getIsImport(), ContactEnum.CUSTOMER_NAME.getAttr(), XbbRefTypeEnum.CONTACT);
//        batchEditContact(saasNeedRedundantAttrPoJo, formDataAddDTO.getLoginUser(), newPaasFormDataEntity);

        try {
            if (isNotDistributeBusinessType(workflowTransferPOJO) && Boolean.FALSE.equals(judgeStageChangedPojo.getIsStageChanged())) {
                PaasFormEntity paasForm = proFormHelp.getPaasForm(pojoData.getFormId(), pojoData.getBusinessType(), corpid);
                String paasFormName = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getName();
                if (Objects.nonNull(paasForm)) {
                    paasFormName = paasForm.getName();
                }
                String creatorUserName = Objects.isNull(creator) ? "" : creator.getName();
                String communicateMemo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.DYNAMIC_USER_UPDATE_BASE_INFO), creatorUserName, paasFormName);
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCustomerId(dataId);
                customerDynamicAddDTO.setCustomerName(customerName);
                customerDynamicAddDTO.setDataId(0L);
                customerDynamicAddDTO.setCommunicateBusinessType(null);
                customerDynamicAddDTO.setCommunicateBusinessText("");
                customerDynamicAddDTO.setLogType(ProjectLogEnum.CUSTOMER_UPDATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCustomerStrategy.update", e);
        }

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException{
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                CustomerEntityExt customerEntityExt = new CustomerEntityExt();
                customerEntityExt.setId(dataId);
                customerEntityExt.setCorpid(corpid);
                customerEntityExt.setData(data);
                customerEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                customerEntityExt.setOwnerId(getOwnerId(data));
                customerEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                List<CustomerUserEntity> contractUserList = JSON.parseArray(data.getString(StringConstant.USER_TEAM), CustomerUserEntity.class);

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    customerEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                customerModel.update(customerEntityExt);
                // 回退被删掉的子表单
                IndexTypeEnum customerSubIndex = indexTypeModel.getCustomerSubIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);

                updateBackSubForm(customerEntityExt, corpid, customerSubIndex);

                saveUserTeam(contractUserList, corpid, customerEntityExt.getId());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCustomerStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            CustomerEntityExt customerEntityExt = new CustomerEntityExt();
            customerEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                customerEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                customerEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            customerEntityExt.setCorpid(corpid);
            customerEntityExt.setUpdateTime(DateTimeUtil.getInt());
            customerModel.update(customerEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;
            IndexTypeEnum customerSubIndex = indexTypeModel.getCustomerSubIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, customerSubIndex, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 团队
            List<CustomerUserEntity> contractUserList = customerUserModel.getByCustomerId(corpid, dataId);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                customerUserModel.deleteBatch(corpid, contractUserList, WriteRequest.RefreshPolicy.NONE, del.getDel());
            }

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCustomerStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 保存团队
     * @param list
     * @param corpid
     * @param dataId
     * @throws XbbException
     */
    private void saveUserTeam(List<CustomerUserEntity> list, String corpid, Long dataId) throws XbbException {

        try {
            List<CustomerUserEntity> contractUserList = customerUserModel.getByCustomerId(corpid, dataId);
            List<Long> idList = new ArrayList<>();
            contractUserList.forEach(item->idList.add(item.getId()));

            contractUserList.removeAll(list);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                customerUserModel.deleteBatch(corpid,contractUserList, WriteRequest.RefreshPolicy.NONE, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                customerUserModel.updateBatch(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCustomerStrategy.saveUserTeam error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

}
